package base.多线程.扩展JUC.信息量;

import java.sql.Time;
import java.util.Random;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

public class Crossroad implements Runnable{
    /*测试Semaphore类的使用*/
    Semaphore semaphore = new Semaphore(2);//允许的数量

    @Override
    public void run() {
        try {
            semaphore.acquire();//获得许可
            System.out.println(Thread.currentThread().getName()+"-正在通过路口");

            Random r = new Random();
            TimeUnit.SECONDS.sleep(r.nextInt(3,7));

            System.out.println(Thread.currentThread().getName()+"-驶出路口...");
            semaphore.release();

        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }
}

class Test{
    public static void main(String[] args){
        Crossroad c1 = new Crossroad();
        for (int i = 0; i < 10; i++) {
            new Thread(c1,"car"+i).start();
        }
    }
}
